package com.awardsystem.Controller;

import com.alibaba.fastjson.JSONObject;
import com.awardsystem.Utils.FileUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@RestController
@CrossOrigin
public class FileController {
    //测试文件传输接口
    @PostMapping("/uploadTest")
    public JSONObject uploadTest(@RequestParam("file") MultipartFile file){
        JSONObject ret=new JSONObject();
        if(file.isEmpty()){
            ret.put("success", false);
            ret.put("exc", "文件为空");
        }else{
            String uuid = UUID.randomUUID().toString();
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();//防止大小写绕过
            String fileName = uuid +  "." + suffix;
            String filePath = System.getProperty("user.dir")+"/upload";//更改为相关目录
            System.out.println(filePath);
            switch (suffix) {
                case "jpg":
                case "png":
                case "jpeg":
                    filePath += "/image";
                    break;
                case "pdf":
                    filePath += "/pdf";
                    break;
                default:
                    filePath += "/other";
            }
            try {
                FileUtils.uploadFileByStream(file.getInputStream(),filePath,fileName);
                ret.put("success", true);
                ret.put("path",fileName);
                ret.put("exc", "上传成功");
            } catch (Exception e) {
                e.printStackTrace();
                ret.put("success", false);
                ret.put("exc", "上传失败");
            }
        }
        return ret;
    }
}
